/*
 * Element.cpp
 *
 *  Created on: 2010-10-26
 *      Author: wenjian
 */

#include "Element.h"
#include "Elements.h"

namespace Ed {

  Element::Element():boundRect(NULL), redrawElements(NULL){


  }

  Element::~Element() {
    if(boundRect)delete boundRect;
    if(redrawElements)delete redrawElements;
  }


//  /**
//   * 构建路径
//   */
//  void Element::createPath(){
//
//  }

  /**
   * 重画与此元素相交的其它元素, 排除<code>excludeds</code>中的元素
   */
  void Element::redrawIntersection(const std::vector<AbstractElement*>* excludeds){
    prepareRedrawElements();
    redrawElements->redrawIntersection(excludeds);
  }

  /**
   * 重画与此元素相交的元素, 包括相交元素和自己, 排除<code>excludeds</code>中的元素
   */
  void Element::redrawAll(const std::vector<AbstractElement*>* excludeds){
    prepareRedrawElements();
    redrawElements->redrawAll(excludeds);
  }

  void  Element::prepareRedrawElements(){
    if(!redrawElements){
      redrawElements = new Elements(this);
      redrawElements->setLayer(layer);
    }
  }

  /**
   * 检查是否与点(x, y)相交
   */
  bool Element::intersects(real x, real y){
    const Gdiplus::RectF* boundrect = this->getBoundRect();
    return boundrect && boundrect->Contains(x, y);
  }

  /**
   * 检查是否与参数矩形区相交
   */
  bool Element::intersects(const Gdiplus::RectF* rect){
    const Gdiplus::RectF* boundrect = this->getBoundRect();
    if(boundrect && rect){
      return boundrect->IntersectsWith(*rect);
    }
    return false;
  }

  /**
   * 检查是否与参数矩形区相交
   */
  bool Element::intersects(const vector<const Gdiplus::RectF*>* rects){
    for(vector<const Gdiplus::RectF*>::const_iterator it = rects->begin(); it != rects->end(); it++){
      if(intersects(*it)){
        return true;
      }
    }
    return false;
  }

  /**
   * 检查是否与元素e相交
   */
  bool Element::intersects(Element* e){
    return Element::intersects(e->getBoundRect());
  }

  /**
   * 检查是否与元素els相交
   */
  bool Element::intersects(const vector<Element*>* els){
    for(vector<Element*>::const_iterator it = els->begin(); it != els->end(); it++){
      if(intersects(*it)){
        return true;
      }
    }
    return false;
  }


  const Gdiplus::RectF* Element::getBoundRect() const{
    return boundRect;
  }

  Gdiplus::RectF* Element::getBoundRect(Gdiplus::RectF* outBoundRect, real adjustVal) const{
    outBoundRect->X = ceil(boundRect->X-adjustVal);
    outBoundRect->Y = ceil(boundRect->Y-adjustVal);
    outBoundRect->Width = ceil(boundRect->Width+adjustVal*2);
    outBoundRect->Height = ceil(boundRect->Height+adjustVal*2);
    return outBoundRect;
  }

  /**
   * 创建包含元素所有可视内容的最大矩形区域
   */
  void Element::createBoundRect(){
    if(boundRect){
        boundRect->X = x();
        boundRect->Y = y();
        boundRect->Width = width();
        boundRect->Height = height();
    }else{
      boundRect = new Gdiplus::RectF(x(), y(), width(), height());
    }
  }
}
